package com.oracle.zebrafreelytraveling.ui;

import android.app.Activity;
import android.content.Intent;
import android.net.Uri;
import android.os.Bundle;
import android.support.annotation.Nullable;
import android.support.v4.widget.SwipeRefreshLayout;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.util.Log;
import android.view.Menu;
import android.view.View;

import com.amap.api.location.AMapLocation;
import com.amap.api.location.AMapLocationClientOption;
import com.amap.api.maps.AMapUtils;
import com.amap.api.maps.model.LatLng;
import com.facebook.drawee.view.SimpleDraweeView;
import com.oracle.zebrafreelytraveling.R;
import com.oracle.zebrafreelytraveling.data.RequestResult.ResFoodInfo;
import com.oracle.zebrafreelytraveling.data.model.IntroBase;
import com.oracle.zebrafreelytraveling.map.MapInfoAdapter;
import com.oracle.zebrafreelytraveling.map.MapUtil;
import com.oracle.zebrafreelytraveling.net.HttpManager;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.CommonAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.MultiItemTypeAdapter;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.base.ViewHolder;
import com.oracle.zebrafreelytraveling.ui.BaseRecycleAdapter.wrapper.LoadMoreWrapper;
import com.oracle.zebrafreelytraveling.ui.fragment.IntroSlideDialogFragment;
import com.oracle.zebrafreelytraveling.utils.ClassInfoUtil;
import com.oracle.zebrafreelytraveling.utils.constant.Constant;
import com.oracle.zebrafreelytraveling.utils.ToastUtil;

import java.util.ArrayList;
import java.util.List;

import io.reactivex.Observer;
import io.reactivex.android.schedulers.AndroidSchedulers;
import io.reactivex.annotations.NonNull;
import io.reactivex.disposables.Disposable;
import io.reactivex.schedulers.Schedulers;

/**
 * Created by yydcnjjw on 2017/7/28.
 * food 分类信息界面
 */

public class ClassifyFoodActivity extends BaseActitvity {

    private RecyclerView mFoodRcycleView;
    private List<ResFoodInfo.ResultBean> mFoodInfoList;
    private CommonAdapter<ResFoodInfo.ResultBean> mFoodRcycleViewAdapter;
    private LoadMoreWrapper mLoadMoreWrapper;
    private ViewHolder mFoodInfoViewHolder;
    private SimpleDraweeView mFoodImage;
    private SwipeRefreshLayout mFoodInfoRefreshLayout;

    private AMapLocation mMapLocation;

    //控制更新的类型 默认上拉加载
    private int updataType = Constant.GET_DATA_TYPE_LOADMORE;

    //记录页数
    private int page = 1;
    private Disposable mDisposable;
    private boolean isDataNull = false;

    private MapUtil mapUtil;

    @Override
    protected void onCreate(@Nullable Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_food_classify);
        initView();
        initMapLocationAndUpdataInfo();
    }

    private void initView() {
        mFoodInfoRefreshLayout = (SwipeRefreshLayout) findViewById(R.id.updata_food_info);
        mFoodInfoRefreshLayout.setOnRefreshListener(() -> {
            updataType = Constant.GET_DATA_TYPE_NOMAL;
            mapUtil.startLocation(MapUtil.LOCATION_ONLY_ONE,
                    AMapLocationClientOption.AMapLocationMode.Hight_Accuracy, 100);
        });
        mFoodRcycleView = (RecyclerView) findViewById(R.id.food_recycle_view);
        mFoodRcycleView.setLayoutManager(new LinearLayoutManager(this));
        mFoodInfoList = new ArrayList<>();
        mFoodRcycleViewAdapter = new CommonAdapter<ResFoodInfo.ResultBean>(this, R.layout.item_food_classify, mFoodInfoList) {
            @Override
            protected void convert(ViewHolder holder, ResFoodInfo.ResultBean resFoodInfo, int position) {
                mFoodImage = holder.getView(R.id.food_image);
                mFoodImage.setImageURI(Uri.parse(resFoodInfo.getPhotos()));
                mFoodImage.setOnClickListener(v -> {

                });
                holder.setText(R.id.food_name, resFoodInfo.getName());
                holder.setText(R.id.food_address, resFoodInfo.getAddress());
                LatLng from = new LatLng(mMapLocation.getLatitude(), mMapLocation.getLongitude());
                LatLng to = new LatLng(Double.parseDouble(resFoodInfo.getLatitude()),
                        Double.parseDouble(resFoodInfo.getLongitude()));
                double distance = AMapUtils.calculateLineDistance(from, to);
                holder.setText(R.id.distance_location, "距离当前位置：" + distance + "M");
            }
        };
        mFoodRcycleViewAdapter.setOnItemClickListener(new MultiItemTypeAdapter.OnItemClickListener() {
            @Override
            public void onItemClick(View view, RecyclerView.ViewHolder holder, int position) {
                IntroBase base = new IntroBase();
                base.setIntroName(mFoodInfoList.get(position).getName());
                base.setIntroImage(mFoodInfoList.get(position).getPhotos());
                base.setIntroContent(mFoodInfoList.get(position).getProduct_rating() + "\n"
                        + mFoodInfoList.get(position).getEnvironment_rating() + "\n"
                        + mFoodInfoList.get(position).getService_rating());
                base.setIntroContact(mFoodInfoList.get(position).getPhone());
                base.setIntroLocation(mFoodInfoList.get(position).getAddress());
                base.setLatitude(mFoodInfoList.get(position).getLatitude());
                base.setLongitude(mFoodInfoList.get(position).getLongitude());
                IntroSlideDialogFragment.newInstance(base, -1).showDialogFragment(getFragmentManager());
            }

            @Override
            public boolean onItemLongClick(View view, RecyclerView.ViewHolder holder, int position) {
                return false;
            }
        });
        LoadMoreWrapper();
        mFoodRcycleView.setAdapter(mLoadMoreWrapper);
    }

    private void LoadMoreWrapper() {
        mLoadMoreWrapper = new LoadMoreWrapper(mFoodRcycleViewAdapter);
        mLoadMoreWrapper.setLoadMoreView(R.layout.footer_loading);
        mLoadMoreWrapper.setOnLoadMoreListener((viewHolder) -> {
            mFoodInfoViewHolder = viewHolder;
            updataType = Constant.GET_DATA_TYPE_LOADMORE;
            if (!isDataNull) {
                mapUtil.startLocation(MapUtil.LOCATION_ONLY_ONE,
                        AMapLocationClientOption.AMapLocationMode.Hight_Accuracy, 0);
            } else {
                viewHolder.getConvertView().setVisibility(View.GONE);
            }

        });
    }

    /**
     * 初始化定位信息
     * 并且更新foodlist
     */
    private void initMapLocationAndUpdataInfo() {
        mapUtil = new MapUtil(new MapInfoAdapter() {
            @Override
            public void locationInfo(AMapLocation location) {
                super.locationInfo(location);
                mMapLocation = location;
                if (location != null) {
                    Log.d("location", location.getAddress());
                    updateFoodInfoList(location);
                } else {
                    Log.d("location", "false");
                    ToastUtil.showToast(getString(R.string.location_false));
                    mFoodInfoViewHolder.getConvertView().setVisibility(View.GONE);
                }

            }
        });
        mapUtil.startLocation(MapUtil.LOCATION_ONLY_ONE,
                AMapLocationClientOption.AMapLocationMode.Hight_Accuracy, 0);
    }

    private void updateFoodInfoList(AMapLocation location) {
        HttpManager.getInstance()
                .getService(Constant.FOOD_API)
                .getFoodInfo(location.getLatitude(), location.getLongitude(), page)
                .subscribeOn(Schedulers.io())
                .observeOn(AndroidSchedulers.mainThread())
                .subscribe(new Observer<ResFoodInfo>() {
                    @Override
                    public void onSubscribe(@NonNull Disposable d) {
                        mDisposable = d;
                    }

                    @Override
                    public void onNext(@NonNull ResFoodInfo resFoodInfo) {
                        ToastUtil.showToast(resFoodInfo.getReason());
                        if (resFoodInfo.getResult() == null || resFoodInfo.getResultcode().equals(Constant.JUHE_SUCCESS)) {
                            isDataNull = true;
                            mFoodInfoViewHolder.getConvertView().setVisibility(View.GONE);
                            return;
                        }
                        if (updataType == Constant.GET_DATA_TYPE_LOADMORE) {
                            mFoodInfoList.addAll(resFoodInfo.getResult());
                            isDataNull = false;
                        } else {
                            mFoodInfoList.clear();
                            mFoodInfoList.addAll(resFoodInfo.getResult());
                        }
                        mLoadMoreWrapper.notifyDataSetChanged();
                    }

                    @Override
                    public void onError(@NonNull Throwable e) {
                        Log.d("foodListUpdataError", e.getMessage());
                        mFoodInfoRefreshLayout.setRefreshing(false);
                        mFoodInfoViewHolder.getConvertView().setVisibility(View.GONE);
                    }

                    @Override
                    public void onComplete() {
                        mFoodInfoRefreshLayout.setRefreshing(false);
                        mFoodInfoViewHolder.getConvertView().setVisibility(View.GONE);
                    }
                });
        // TODO 模拟数据
        mFoodInfoList.addAll(ClassInfoUtil.getFoodList());
        mLoadMoreWrapper.notifyDataSetChanged();
        page++;
    }

    @Override
    protected void onDestroy() {
        super.onDestroy();
        //清除 Disposable
        if (mDisposable != null && !mDisposable.isDisposed()) {
            mDisposable.dispose();
        }
        page = 0;
    }

    @Override
    protected int getLayoutId() {
        return R.layout.activity_food_classify;
    }


    public static void startFoodClassifyActivity(Activity activity) {
        Intent i = new Intent(activity, ClassifyFoodActivity.class);
        activity.startActivity(i);
    }

    @Override
    public boolean onCreateOptionsMenu(Menu menu) {
        getMenuInflater().inflate(R.menu.menu_food_activity, menu);
        return true;
    }
}
